package com.xxl.job.admin.core.scheduler;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.thread.*;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.client.ExecutorBizClient;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 任务调度器
 * @author xuxueli 2018-10-28 00:18:17
 */

public class XxlJobScheduler  {
    private static final Logger logger = LoggerFactory.getLogger(XxlJobScheduler.class);

    /**
     * 1.加载国际化配置
     * 2.启动两个 线程池，用于 触发任务
     * 3. 启动 管理注册执行器 的线程
     * 4. 启动 处理失败任务，触发报警 的线程
     * 5. 启动处理“丢失”任务的线程
     * 6. 启动生成调度报表数据的线程
     * 7. 启动两个 调度器 线程，一个处理粗粒任务，另一个使用时间轮处理秒级粒度任务。
     * @throws Exception
     */
    public void init() throws Exception {
        // 1. init i18n
        initI18n();

        // 2.admin trigger pool start
        // Trigger 线程池的辅助类：管理 Trigger 线程池、添加 trigger 线程到线程池 启动两个线程池，用于触发任务
        JobTriggerPoolHelper.toStart();

        // 3.admin registry monitor run
        // executor 注册和下线的辅助类
        JobRegistryHelper.getInstance().start();

        // 4. admin fail-monitor run
        // Job 执行失败的监视线程辅助类 启动处理失败任务，触发报警的线程
        JobFailMonitorHelper.getInstance().start();

        // 5.admin lose-monitor run ( depend on JobTriggerPoolHelper )
        // 启动处理“丢失”任务的线程 Job 完成线程的辅助类
        JobCompleteHelper.getInstance().start();

        // 6. admin log report start
        // Job 日志统计辅助类
        // admin log report start 启动生成调度报表数据的线程
        JobLogReportHelper.getInstance().start();

        // 7. start-schedule  ( depend on JobTriggerPoolHelper )
        // Job 调度辅助类
        // 启动两个调度器线程，一个处理粗粒任务，另一个使用时间轮处理秒级粒度任务
        JobScheduleHelper.getInstance().start();

        logger.info(">>>>>>>>> init xxl-job admin success.");
    }

    
    public void destroy() throws Exception {

        // stop-schedule
        JobScheduleHelper.getInstance().toStop();

        // admin log report stop
        JobLogReportHelper.getInstance().toStop();

        // admin lose-monitor stop
        JobCompleteHelper.getInstance().toStop();

        // admin fail-monitor stop
        JobFailMonitorHelper.getInstance().toStop();

        // admin registry stop
        JobRegistryHelper.getInstance().toStop();

        // admin trigger pool stop
        JobTriggerPoolHelper.toStop();

    }

    // ---------------------- I18n ----------------------

    private void initI18n(){
        for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) {
            item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
        }
    }

    // ---------------------- executor-client ----------------------
    private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String, ExecutorBiz>();
    public static ExecutorBiz getExecutorBiz(String address) throws Exception {
        // valid
        if (address==null || address.trim().length()==0) {
            return null;
        }

        // load-cache
        address = address.trim();
        ExecutorBiz executorBiz = executorBizRepository.get(address);
        if (executorBiz != null) {
            return executorBiz;
        }

        // set-cache
        executorBiz = new ExecutorBizClient(address, XxlJobAdminConfig.getAdminConfig().getAccessToken());

        executorBizRepository.put(address, executorBiz);
        return executorBiz;
    }

}
